<template>
  <div class="goods-box w-card">
    <div class="content-box">
      <div class="content-title">
        <h1>商品列表</h1>
        <el-button style="margin-left:auto;" type="primary" @click="addGoods">新增商品</el-button>
      </div>
      <div class="content-table">
        <div class="search-box">
          <div class="form-item">
            <span>商品名称：</span>
            <el-input v-model="searchForm.goodsName" clearable placeholder="请输入商品名称" />
          </div>
          <div class="form-item">
            <span>类型：</span>
            <el-select style="width:100%" v-model="searchForm.typeId" clearable @change="typeChange">
              <el-option v-for="item in typeOptions" :key="item.typeId" :label="item.typeName" :value="item.typeId" />
            </el-select>
          </div>
          <div class="form-item">
            <span>分类：</span>
            <el-select style="width:100%" v-model="searchForm.categoryId" clearable no-data-text="请先选择类型" @change="cateChange">
              <el-option v-for="item in simpleOptions" :key="item.categoryId" :label="item.categoryName"
                :value="item.categoryId" />
            </el-select>
          </div>
          <div class="form-item">
            <span>品牌：</span>
            <el-select style="width:100%" v-model="searchForm.brandId" clearable no-data-text="请先选择分类">
              <el-option v-for="item in brandOptions" :key="item.brandId" :label="item.brandName" :value="item.brandId" />
            </el-select>
          </div>
        </div>
        <div class="search-box" style="margin-top:20px">
          <div class="form-item">
            <span>渠道：</span>
            <el-select style="width:100%" v-model="searchForm.channelCode" clearable no-data-text="请选择渠道">
              <el-option v-for="item in qudaoOptions" :key="item.channelCode" :label="item.channelName"
                :value="item.channelCode" />
            </el-select>
          </div>
          <div class="form-item">
            <span>商品状态：</span>
            <el-select style="width:100%" v-model="searchForm.goodsStatus" clearable>
              <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </div>
          <div class="form-item" style="width:30% !important;max-width:400px;">
            <span>开通时间：</span>
            <el-date-picker v-model="searchForm.date" type="datetimerange" range-separator="至" start-placeholder="开始时间"
              end-placeholder="结束时间" />
          </div>
          <el-button type="primary" @click="searchHandle">搜索</el-button>
          <el-button style="margin-left:auto;" @click="inHandle(1)">新增导入</el-button>
          <el-button style="margin-left:0;" @click="inHandle(2)">修改导入</el-button>
          <el-button style="margin-left:0;" @click="inHandle(3)" :loading="loading">导出商品</el-button>
        </div>
        <div class="table-box">
          <el-table :height="tableHeight" :header-cell-style="{background:'#d6dee5',color:'#000000',fontSize:'14px'}"
            :cell-style="{fontSize:'14px',color:'#7b7b7d'}" :data="tableData" stripe @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="30" />
            <el-table-column type="index" width="55" label="序号" align="center" />
            <el-table-column prop="goodsName" label="商品名称" align="center" min-width="140">
              <template v-slot="scope">
                <el-link type="primary" @click="lookDetail(scope.row)">{{ scope.row.goodsName || '' }}</el-link>
              </template>
            </el-table-column>
            <el-table-column prop="typeName" label="商品类型" align="center">
              <template v-slot="scope">
                {{ scope.row.typeName || '' }}
              </template>
            </el-table-column>
            <el-table-column prop="categoryName" label="商品分类" align="center">
              <template v-slot="scope">
                {{ scope.row.categoryName || '' }}
              </template>
            </el-table-column>
            <el-table-column prop="brandName" label="商品品牌" align="center" min-width="120">
              <template v-slot="scope">
                {{ scope.row.brandName || '' }}
              </template>
            </el-table-column>
            <el-table-column prop="channelName" label="渠道信息" align="center" min-width="160">
              <template v-slot="scope">
                <div class="qdxx">
                  <div style="display: flex;align-items: center;justify-content: center;flex-wrap: wrap;"
                    v-for="item in scope.row?.channelProductList" :key="item">
                    <div>
                      <span>{{ item.channelName }}：</span>
                      <span>{{ item.channelPrice }}元</span>
                    </div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <!-- <el-table-column prop="shopName" label="品类" align="center" min-width="200">
              <template v-slot="scope">
                <span>{{ scope.row.brandName }}</span>
                <span>【{{ scope.row.typeName + '-' + scope.row.categoryName }}】</span>
              </template>
            </el-table-column> -->
            <!-- <el-table-column prop="channelPrice" label="上游成本价(元)" align="center" width="120">
              <template v-slot="scope">
                {{ numFormat(scope.row.channelPrice) || '' }}
              </template>
            </el-table-column> -->
            <el-table-column prop="officialPrice" label="官方价(元)" align="center" min-width="100">
              <template v-slot="scope">
                {{ numFormat(accDiv((scope.row?.officialPrice || 0),10000)) || '' }}
              </template>
            </el-table-column>
            <el-table-column prop="costPrice" label="成本价(元)" align="center" min-width="160">
              <template v-slot="scope">
                {{ numFormat(accDiv((scope.row?.costPrice || 0),10000)) || '' }}
                <div>
                  <div v-for="item in (scope.row?.costPriceShop || [])" :key="item">
                    <span>{{ item.shopName }}：</span>
                    <span>{{ item.price }}元</span>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="discountPrice" label="折扣价(元)" align="center" min-width="160">
              <template v-slot="scope">
                {{ numFormat(accDiv((scope.row?.discountPrice || 0),10000)) || '' }}
                <div>
                  <div v-for="item in (scope.row?.discountPriceShop || [])" :key="item">
                    <span>{{ item.shopName }}：</span>
                    <span>{{ item.price }}元</span>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="suggestPrice" label="建议(元)" align="center" min-width="100">
              <template v-slot="scope">
                {{ numFormat(accDiv((scope.row?.suggestPrice || 0),10000)) || '' }}
              </template>
            </el-table-column>
            <el-table-column prop="finalStatus" label="状态" align="center" width="100">
              <template v-slot="scope">
                <span :class="'state'+scope.row.finalStatus"></span>
                {{ scope.row.finalStatus == 0 ? '下架' : '销售中' }}
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="上架时间" align="center" width="170">
              <template v-slot="scope">
                {{ scope.row.createTime ? getDateTime(scope.row.createTime)[6] : '' }}
              </template>
            </el-table-column>
            <el-table-column prop="operations" label="操作" align="center" width="160" fixed="right">
              <template v-slot="scope">
                <el-link style="font-size:14px;" type="primary" @click="editHandle(scope.row)">编辑</el-link>
                <el-link v-if="scope.row.finalStatus == 0" style="font-size:14px;margin-left:10px;" type="primary"
                  @click="handleClick(1,scope.row)">上架</el-link>
                <el-link v-if="scope.row.finalStatus == 1" style="font-size:14px;margin-left:10px;" type="danger"
                  @click="handleClick(2,scope.row)">下架</el-link>
                <el-link style="font-size:14px;margin-left:10px;" type="danger" @click="handleClick(3,scope.row)">删除</el-link>
              </template>
            </el-table-column>
          </el-table>
          <div class="table-footer">
            <div>
              <el-button :disabled="chooseList.length == 0" type="warning" plain @click="handleClick(1)">批量上架</el-button>
              <el-button :disabled="chooseList.length == 0" plain @click="handleClick(2)">批量下架</el-button>
              <el-button :disabled="chooseList.length == 0" plain @click="handleClick(3)">批量删除</el-button>
            </div>
            <el-pagination v-model:currentPage="page" v-model:page-size="size" :page-sizes="[10, 20, 50, 100]" small
              :background="true" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
              @current-change="handleCurrentChange" />
          </div>
        </div>
      </div>
    </div>
  </div>
  <confirm-pass ref="confirmPassRef" @verification="verification" />
  <in-out-dialog ref="inOutDialogRef" @dialogClose="inOutClose" />
</template>

<script>
import { onMounted, reactive, ref, toRefs } from 'vue'
import { getWindowWidthAndHeight, warningDeal, getDateTime, numFormat, BlobDownLoad, accDiv } from '@/utils/utils'
import confirmPass from '@/components/confirmPass.vue'
import api from './api'
import router from '@/router'
import inOutDialog from '../components/inOutDialog.vue'
export default {
  components: {
    confirmPass,
    inOutDialog,
  },
  setup() {
    const confirmPassRef = ref(null)

    const inOutDialogRef = ref(null)

    const state = reactive({
      loading: false,
      page: 1,
      size: 10,
      total: 0,
      tableHeight: 0,
      handleClickType: null,
      handleClickData: null,
      searchForm: {},
      tableData: [],
      chooseList: [],
      statusOptions: [
        {
          value: 1,
          label: '销售中',
        },
        {
          value: 0,
          label: '下架',
        },
      ],
      typeOptions: [],
      simpleOptions: [],
      brandOptions: [],
      qudaoOptions: [],
    })

    function getQudaoOptions() {
      const obj = {
        page: 1,
        size: 1000,
      }
      api.channelList(obj).then(res => {
        if (res.code == '200') {
          state.qudaoOptions = res.data.list
        } else {
          warningDeal(res.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    }

    function typeChange(e) {
      state.searchForm.categoryId = null
      state.searchForm.brandId = null
      if (!e) {
        state.simpleOptions = []
        state.brandOptions = []
      }
      getSimOptions(e)
    }

    function cateChange(e) {
      state.searchForm.brandId = null
      if (!e) {
        state.brandOptions = []
      }
      goodsBrandSimple(e)
    }

    function getSimOptions(typeId) {
      const obj = {
        typeId
      }
      api.goodsCategoryListSimple(obj).then(res => {
        if (res.code == '200') {
          state.simpleOptions = res.data
        } else {
          warningDeal(res.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    }

    function getTypeOptions() {
      api.goodsTypeListSimple().then(res => {
        if (res.code == '200') {
          state.typeOptions = res.data
        } else {
          warningDeal(res.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    }

    function goodsBrandSimple(categoryId) {
      const obj = {
        categoryId
      }
      api.goodsBrandSimple(obj).then(res => {
        if (res.code == '200') {
          state.brandOptions = res.data
        } else {
          warningDeal(res.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    }

    function handleSizeChange(e) {
      state.size = e
      getTableData()
    }

    function handleCurrentChange(e) {
      state.page = e
      getTableData()
    }

    function getTableData() {
      const obj = {
        page: state.page,
        size: state.size,
        ...state.searchForm,
        startTime: (state.searchForm.date && state.searchForm.date.length > 0) ? state.searchForm.date[0].getTime() : null,
        endTime: (state.searchForm.date && state.searchForm.date.length > 0) ? state.searchForm.date[1].getTime() : null,
      }
      api.goodsInfoSearch(obj).then(res => {
        if (res.code == '200') {
          state.tableData = res.data.records
          state.total = res.data.total
        } else {
          warningDeal(res.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    }

    function inOutClose() {
      getTableData()
    }

    function handleClick(i, data) {
      state.handleClickType = i
      state.handleClickData = data || null
      let title = ''
      let msg = ''
      switch (i) {
        case 1:
          //上架
          title = '上架提示'
          msg = '是否确定上架选中商品？'
          break
        case 2:
          //下架
          title = '下架提示'
          msg = '是否确定下架选中商品？'
          break
        case 3:
          //删除
          title = '删除提示'
          msg = '是否确定删除选中商品？'
          break
      }
      confirmPassRef.value.dialogShow(title, msg, false)
    }

    function getGoodsIds(list) {
      const myArr = []
      list && list.map(item => {
        item.goodsId && myArr.push(item.goodsId)
      })
      return myArr
    }

    function verification() {
      let goodsIds = []
      if (state.handleClickData) {
        goodsIds = [state.handleClickData.goodsId]
      } else {
        goodsIds = getGoodsIds(state.chooseList)
      }
      let goodsStatus = null
      switch (state.handleClickType) {
        case 1:
          //上架
          goodsStatus = 1
          goodsStateChange(goodsIds, goodsStatus)
          break
        case 2:
          //下架
          goodsStatus = 0
          goodsStateChange(goodsIds, goodsStatus)
          break
        case 3:
          //删除
          deleteGoods(goodsIds)
          break
      }
    }

    function goodsStateChange(goodsIds, goodsStatus) {
      const obj = {
        goodsIds,
        goodsStatus,
      }
      api.goodsInfoModifyStatus(obj).then(res => {
        if (res.code == '200') {
          getTableData()
        } else {
          warningDeal(res.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    }

    function deleteGoods(goodsIds) {
      const obj = {
        goodsIds
      }
      api.goodsInfoDelete(obj).then(res => {
        if (res.code == '200') {
          getTableData()
        } else {
          warningDeal(res.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    }

    function searchHandle() {
      state.page = 1
      getTableData()
    }

    function addGoods() {
      router.push({ path: '/goods/add' })
    }

    function handleSelectionChange(e) {
      state.chooseList = e
    }

    function editHandle(data) {
      router.push({ path: '/goods/edit', query: { goodsId: data.goodsId } })
    }

    function lookDetail(data) {
      router.push({ path: '/goods/details', query: { goodsId: data.goodsId } })
    }

    function inHandle(i) {
      switch (i) {
        case 1:
          //新增
          inOutDialogRef.value.dialogShow(i)
          break
        case 2:
          //修改
          inOutDialogRef.value.dialogShow(i)
          break
        case 3:
          //导出
          if (state.loading) return
          state.loading = true
          const obj = {
            page: state.page,
            size: state.size,
            ...state.searchForm,
            startTime: (state.searchForm.date && state.searchForm.date.length > 0) ? state.searchForm.date[0].getTime() : null,
            endTime: (state.searchForm.date && state.searchForm.date.length > 0) ? state.searchForm.date[1].getTime() : null,
          }
          api.goodsInfoDown({ ...obj, responseType: "blob" }).then(res => {
            const _fileName = decodeURIComponent(res.headers['content-disposition'].split(';')[1].split('=')[1])
            BlobDownLoad(res, _fileName)
            state.loading = false
          }).catch(err => {
            console.log(err)
            state.loading = false
          })
          break
      }
    }

    onMounted(() => {
      let winHeight = getWindowWidthAndHeight()
      state.tableHeight = winHeight.windowHeight - 340
      getTableData()
      getTypeOptions()
      getQudaoOptions()
    })

    return {
      ...toRefs(state),
      confirmPassRef,
      inOutDialogRef,
      handleSizeChange,
      handleCurrentChange,
      handleClick,
      verification,
      getDateTime,
      searchHandle,
      typeChange,
      cateChange,
      addGoods,
      numFormat,
      handleSelectionChange,
      editHandle,
      lookDetail,
      inHandle,
      inOutClose,
      accDiv,
    }
  }
}
</script>

<style lang="scss" scoped>
.goods-box {
  width: 100%;
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-flow: column;
  .content-box {
    flex-grow: 1;
    box-sizing: border-box;
    padding: 20px;
    .content-title {
      display: flex;
      align-items: center;
      > h1 {
        font-size: 16px;
      }
    }
    .content-table {
      margin-top: 20px;
      .search-box {
        display: flex;
        align-items: center;
        gap: 20px;
        .form-item {
          width: 25%;
          max-width: 300px;
          display: flex;
          align-items: center;
          gap: 5px;

          > span {
            font-size: 14px;
            flex-shrink: 0;
          }
        }
      }
      .table-box {
        margin-top: 20px;
        .table-footer {
          margin-top: 20px;
          display: flex;
          align-items: center;
          justify-content: space-between;
        }
      }
    }
  }
}
.state0 {
  display: inline-block;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background-color: #ff3939;
}
.state1 {
  display: inline-block;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background-color: #03b615;
}
</style>